package com.zhang.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

public class ReflectUtils {
    /**
     * 反射覆盖
     */
    public static void saveOrUpdate(Object s1, Object s2) throws Exception {
        Class<?> c1 = s1.getClass();
        Class<?> c2 = s2.getClass();
        Field[] fields = c1.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName(); // 获取属性的名字
            name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
            String type = field.getGenericType().toString(); // 获取属性的类型
            if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
                Method m = c2.getMethod("get" + name);
                String value = (String) m.invoke(s2); // 调用getter方法获取属性值
                field.set(s1, value);
            }
            if (type.equals("class java.lang.Integer")) {
                Method m = c2.getMethod("get" + name);
                Integer value = (Integer) m.invoke(s2);
                field.set(s1, value);
            }

            if (type.equals("class java.lang.Boolean")) {
                Method m = c2.getMethod("get" + name);
                Boolean value = (Boolean) m.invoke(s2);
                field.set(s1, value);
            }
            if (type.equals("class java.util.Date")) {
                Method m = c2.getMethod("get" + name);
                Date value = (Date) m.invoke(s2);
                field.set(s1, value);
            }
        }

    }

    public static void main(String[] args) {
        Student s1 = new Student(1, "张三", 24, "男");
        Student s2 = new Student("赵薇", 38, "女");
        try {
            saveOrUpdate(s1, s2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(s1.toString());
    }
}
